/**
 * @file tools.c
 * @author MTF-1
 *
 * @date 23-01-2011 DD-MM-YYYY
 * @version 0.5
 *
 * @section DESCRIPTION
 *
 * Supporting tools for the other functions of the client.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "tools.h"

#define ERROR 1
#define NOERROR 0
#define CMDAMOUNT 11

/**
 * Get input from the command line.
 *
 * @param ptr_sCmdLine Pointer to a string variable which holds the input.
 * @param size Size of the string variable.
 * @return 1 on error and 0 on no error.
 * @author Rik Janssen
 */
int getCommand(char *ptr_sCmdLine, int size)
{
    /*Show cursor*/
    printf("Command:> ");

    if(fgets(ptr_sCmdLine, size, stdin))
    {
        if(!strcmp(ptr_sCmdLine, "\n"))
        {
            return ERROR; /*User didn't enter anything*/
        }
        ptr_sCmdLine[strlen(ptr_sCmdLine)-1] = '\0'; /*Replace newline with NULL char*/

        return NOERROR;
    }

    return ERROR; /*fgets failed*/
}

/**
 * Get the command number.
 *
 * @param ptr_sCmd Command to look for.
 * @param ptr_iCmdNum Set this variable with the command number if command is found.
 * @return 1 on error (command not found) and 0 on no error(command found).
 * @author Rik Janssen
 */
int getCmdNum(char *ptr_sCmd, int *ptr_iCmdNum)
{
    const char sCommands[CMDAMOUNT][12] = {{"exit"}, {"connect"}, {"disconnect"}, {"info"}, {"help"}, {"upload"}, {"download"}, {"list"}, {"remove"}, {"cd"}, {"clear"}};
    int i;

    /*Look if entered command (*ptr_sCmd) exists*/
    for(i=0; i<CMDAMOUNT; i++)
    {
        if(!strcasecmp(ptr_sCmd, &sCommands[i][0]))
        {
            *ptr_iCmdNum = i; /*Command found*/
            return NOERROR;
        }
    }

    return ERROR; /*Command not found*/
}

/**
 * Split str on character c in max amount of words.
 * After running word contains pointers to each seperate word.
 *
 * @param str String to split.
 * @param word Array of pointers. Each points to a seperate word.
 * @param max Max. amount of words.
 * @param c Character to split on.
 * @return Number of words after split.
 * @author MPNA
 */
int split(char *str, char *word[], int max, char c)
{
    int n = 0;

    do
    {
        while(*str==c)
        {
            str++;
        }

        if(!*str || n==max)
        {
            return n;
        }

        word[n++] = str++;

        while(*str && *str!=c)
        {
            str++;
        }

        if(!*str)
        {
            return n;
        }

        *str++='\0';
    }
    while(1);
}
